package com.lfd.mqttv3.mqtt;

import com.lfd.mqttv3.properties.MqttProperties;
import com.lfd.mqttv3.properties.MqttProperties2;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @项目名： spring-emq
 * @包名： com.lfd.mqttv3.mqtt
 * @文件名: MqttPublisher
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/10/5 14:12
 * @描述：
 */
@Component
@Slf4j
public class MqttPublisher {
    @Autowired
    private MqttProperties2 mqttProperties;
    String broker = "tcp://localhost:1883"; // MQTT 服务器地址
    String clientId = "JavaPublisher"; // 客户端ID
    String topic = "test/topic"; // 发布的主题
    String content = "Hello MQTT!"; // 发布的消息内容
    int qos = 2; // 服务质量
    private MqttClient mqttClient = null;

    public void mqttClient(String content, int qos) throws MqttException {
        // 创建MQTT客户端
        mqttClient = new MqttClient(mqttProperties.getBrokerUrl()
                , mqttProperties.getClientId());
        log.info("MqttPublisher to BrokerUrl: {}", mqttProperties.getBrokerUrl());
        log.info("MqttPublisher to ClientId: {}", mqttProperties.getClientId());

        // 创建连接选项
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(mqttProperties.getUsername());
        // 设置密码，必须是字符数组
        mqttConnectOptions.setPassword(mqttProperties.getPassword().toCharArray());

        // 使用带有认证信息的选项连接到MQTT服务器
        mqttClient.connect(mqttConnectOptions);
//        // 连接到MQTT服务器
//        mqttClient.connect();
        // 创建消息
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        //发布消息
        mqttClient.publish(mqttProperties.getSendTopic(), message);
        log.info("MqttPublisher mqtt client published");
    }

    public void disconnect() throws MqttException {

        // 断开连接
        if (mqttClient != null) {
            mqttClient.disconnect();
        }
    }
}
